<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /**
       * @param {number} n
       * @return {string}
       */
      var countAndSay = function (n) {
        // 递归出口
        if (n === 1) return "1";
        // 获取上一次返回结果
        str = countAndSay(n - 1);
        // var str = "1";
        var nums = [];
        // 将上一次返回结果遍历成数组
        for (var i = 0; i < str.length; i++) {
          nums.push(Number(str[i]));
        }

        str = "";
        // 定义一个索引记录上次统计的数字地方
        var index = 0;
        for (var j = 0; j < nums.length; j++) {
          if (nums[j] !== nums[j + 1]) {
            str = str + (j - index + 1) + nums[j];
            // 从index开始统计个数
            index = j + 1;
          }
        }
        return str;
      };

      var n = 30;
      console.log(countAndSay(n));
    </script>
  </body>
</html>
